locked
Regular expressions. RRS feed

  • Question

  • User-1694438709 posted

    I'm currently looking into Regular Expressions to validate fields within a form. What's the best way to handle these? having them in the Front  End?having them in the Back End? or Both?

    A quick google has given me this website regexr which contains different patterns to play around with.

    So for the purpose of learning and testing how these work I'm trying to get an email validation to work on a registration form and have got the following using a Regex Expression within my model:

    [EmailAddress]
    [Required(ErrorMessage = "Email id is required")]
    [RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Please enter a correct email Address")]
    public string Email { get; set; }

    As it stands I'm not getting prompted for  a wrong format of email getting entered into the field or an empty email field being left within the form.


    Friday, July 17, 2020 12:57 PM

Answers

  • User-821857111 posted

    When it comes to validation, front end is optional, back end is required. If you are using .NET Core, you have to include the ValidationScriptsPartial in the view/page to enable data annotation validation on the client. And you need to test ModelState.IsValid and return the View/Page on the server if it is false.

    Here's an article on validation in Razor Pages. The concepts are the same for MVC views: https://www.learnrazorpages.com/razor-pages/validation

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 19, 2020 7:43 AM
  • User1535942433 posted

    Hi binaary,

    As far as I think,if you need to validate form in the front end,you could use jquery.At the same time ,you could validate them in the back end.

    Accroding to your codes,I have create a test and have the same status,I suggest you have rewrite your Regex expression.

    Replace:

    [EmailAddress]
    [Required(ErrorMessage = "Email id is required")]
    [RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Please enter a correct email Address")]
    public string Email { get; set; }

    With:

    [EmailAddress]
    [Required(ErrorMessage = "Email id is required")] [RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", ErrorMessage = "Please enter a valid email address")]
    public string EmailId
    {
    get;
    set;
    }

    Or:

     [EmailAddress]
     [Required(ErrorMessage = "Email Address is required")]
     [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
            ErrorMessage = "Please enter a valid email address")]
       public string EmailId { get; set; }

    Since you don't post full codes to us,I have create a demo.

    Just like this:

    Index:

    @model WebApplication1.Model.Validate
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <style type="text/css">
            body {
                font-family: Arial;
                font-size: 10pt;
            }
    
            .error {
                color: red;
            }
        </style>
    </head>
    <body>
        @using (Html.BeginForm("Index", "FormRegular", FormMethod.Post))
        {
            <table>
                <tr>
                    <td>Email</td>
                    <td>@Html.TextBoxFor(m => m.EmailId)</td>
                    <td>@Html.ValidationMessageFor(m => m.EmailId, "", new { @class = "error" })</td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Submit" /></td>
                    <td></td>
                </tr>
            </table>
        }
    </body>
    </html>
    

    Controller:

     public class FormRegularController : Controller
        {
            // GET: FormRegular
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Index(Validate person)
            {
                return View();
            }
        }

    Model:

     public class Validate
        {
            [EmailAddress]
            [Required(ErrorMessage = "Email id is required")]
            [RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
                                ErrorMessage = "Please enter a valid email address")]
            public string EmailId
            {
                get;
                set;
            }
        }

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 20, 2020 5:35 AM

All replies

  • User-821857111 posted

    When it comes to validation, front end is optional, back end is required. If you are using .NET Core, you have to include the ValidationScriptsPartial in the view/page to enable data annotation validation on the client. And you need to test ModelState.IsValid and return the View/Page on the server if it is false.

    Here's an article on validation in Razor Pages. The concepts are the same for MVC views: https://www.learnrazorpages.com/razor-pages/validation

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 19, 2020 7:43 AM
  • User1535942433 posted

    Hi binaary,

    As far as I think,if you need to validate form in the front end,you could use jquery.At the same time ,you could validate them in the back end.

    Accroding to your codes,I have create a test and have the same status,I suggest you have rewrite your Regex expression.

    Replace:

    [EmailAddress]
    [Required(ErrorMessage = "Email id is required")]
    [RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", ErrorMessage = "Please enter a correct email Address")]
    public string Email { get; set; }

    With:

    [EmailAddress]
    [Required(ErrorMessage = "Email id is required")] [RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", ErrorMessage = "Please enter a valid email address")]
    public string EmailId
    {
    get;
    set;
    }

    Or:

     [EmailAddress]
     [Required(ErrorMessage = "Email Address is required")]
     [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",
            ErrorMessage = "Please enter a valid email address")]
       public string EmailId { get; set; }

    Since you don't post full codes to us,I have create a demo.

    Just like this:

    Index:

    @model WebApplication1.Model.Validate
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <style type="text/css">
            body {
                font-family: Arial;
                font-size: 10pt;
            }
    
            .error {
                color: red;
            }
        </style>
    </head>
    <body>
        @using (Html.BeginForm("Index", "FormRegular", FormMethod.Post))
        {
            <table>
                <tr>
                    <td>Email</td>
                    <td>@Html.TextBoxFor(m => m.EmailId)</td>
                    <td>@Html.ValidationMessageFor(m => m.EmailId, "", new { @class = "error" })</td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Submit" /></td>
                    <td></td>
                </tr>
            </table>
        }
    </body>
    </html>
    

    Controller:

     public class FormRegularController : Controller
        {
            // GET: FormRegular
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Index(Validate person)
            {
                return View();
            }
        }

    Model:

     public class Validate
        {
            [EmailAddress]
            [Required(ErrorMessage = "Email id is required")]
            [RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
                                ErrorMessage = "Please enter a valid email address")]
            public string EmailId
            {
                get;
                set;
            }
        }

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 20, 2020 5:35 AM