jquery validate form code example

Example 1: jquery validation example

reference : https://www.sitepoint.com/basic-jquery-form-validation-tutorial/

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='registration']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
      password: {
        required: true,
        minlength: 5
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",
      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      email: "Please enter a valid email address"
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});

Example 2: jquery validator Url

$.validator.addMethod("UrlVal", function (value, element) {

            var Inicio_URL = ['http://www', 'https://www', 'www', 'ftp://www'];
            var Fim_URL = ['com', 'net', 'org', 'pt', 'eu','co'];

            var Url_Inserido = value.toLowerCase().split(".");

            if (Inicio_URL.includes(Url_Inserido[0])) {

                if (Fim_URL.includes(Url_Inserido[(Url_Inserido.length - 1)])) {
                    return true;
                } else
                    return false;

            } else
                return false;

        
        })

Example 3: invoking jquery validator

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        // rules & options
    });

    $('#button').click(function() {
        if ($('#myform').valid()) {
            alert('form is valid - not submitted');
        } else {
            alert('form is not valid');
        }
    });

});

Example 4: jquery form validation

function submitFunction(event){
	event.preventDefault();
}
$("#form_id").submit(submitFunction);

Example 5: jquery validate

$("#myform").validate({
  debug: true
});