0

I am attempting to validate an email input that is created with an HTML helper class. The 'validateForm' method is being called properly everytime, but the if statement keeps failing. My two best theories are that my Regex, that I found here, is off due to me having to escape the '@' characters, or I'm not properly comparing it.

Thanks always!

Javascript:

function validateForm() {
    var isValid = true;
    var errorMessage = "";
    var emailRegExp = /^(([^<>()[\]\\.,;:\s@@\"]+(\.[^<>()[\]\\.,;:\s@@\"]+)*)|(\".+\"))@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var x = document.forms["Update"]["complaint.Responsible"].value;

    if (x === null || x === "" || !emailRegExp.test(x)) {
        errorMessage += "A valid 'Responsible' was not entered<br/>";
        document.getElementById("Responsible").style.borderColor = '#F00';
        alert("No! >:(");
        isValid = false;
    }

    return isValid;
}

Form CSHTML:

@Html.TextBoxFor(model => Model.complaint.Responsible, new { @Class = "txtLong" })

Form HTML:

<form name="Update" onsubmit="return validateForm()" method="post" id="formBody"  enctype="multipart/form-data">
     <input class="txtLong" id="complaint_Responsible" name="complaint.Responsible" type="text" value="sdbsv rszaer gse er">

Update:

This is why I can't use a single '@' symbol enter image description here

(one line - as is in code)

enter image description here

Community
  • 1
  • 1
Racksickle
  • 53
  • 2
  • 13

1 Answers1

0

The @@ is telling the regex engine that you expect two @ symbols. Replace it with the pattern below:

var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Mario J Vargas
  • 1,185
  • 6
  • 12
  • I can't use one '@' symbol because the Razer view engine, or MVC I'm not quite sure, treats any '@' symbol as the beginning to C# server-side code. See the image(s) I added in update. – Racksickle May 23 '14 at 17:18
  • 1
    Oh, good point. In that case, can you put the JavaScript in a separate JS file and then reference it with the `SCRIPT` tag? – Mario J Vargas May 23 '14 at 17:25
  • That's a clever idea! Thanks! I wonder if there is a way to convert a C# '@' to a javascript '@' char though? Perhaps with JSON or something like that. – Racksickle May 23 '14 at 17:36