Search code examples
javascriptjqueryregexjquery-form-validator

How to add pattern RegEx for Form validation?


I have a registration form, in which I have used JavaScript form validator

My form

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <form class="form-group" method="post" id="contact-form">
        {% csrf_token %}

        <input type"text" name="username" placeholder="userid" id="id_username"/>
        <input type"email" name="email" placeholder="email" id="id_email"/>
        <input type"password" name="password1" placeholder="password1" id="id_password1"/>
        <input type"password" name="password2" placeholder="password2" id="id_password2"/>
        <input type="address" name="address" placeholder="address" id="id_address"/>

        <input type="submit"/>

    </from>

JavaScript

<script type="text/javascript">

$(document).ready(function () {

    $('#contact-form').validate({
        rules: {
            username: {
                minlength: 5,
                required: true
            },
            email: {
                required: true,
                email: true
            },
            password1: {
                minlength: 6,
                required: true
            },
            password2: {
                required: true,
                minlength: 6,
                equalTo: "#password1",
            },
          address: {
                minlength: 5,
                required: true,

            },
        },
        highlight: function (element) {
            $(element).closest('.control-group').removeClass('success').addClass('error');
        },
        success: function (element) {
            element.text('OK!').addClass('valid')
                .closest('.control-group').removeClass('error').addClass('success');
        }
    });

   });

I want to RegEx pattern to address like only /-()., these charters are only allowed with alphabets how do I use pattern RegEx in this?


Solution

  • try this

    address: {
                minlength: 5,
                maxlenght=50,
                required: true,
                regex: /^[a-zA-Z0-9\s,'-./()]*$/,
            },