Custom Validation in js plugin

I am building a webpage and have built some custom validation into it for phone numbers but now I have been asked can I do it on the client side as well. I have been looking up how to build a jquery plugin and honestly this is the first time I have ever attempted something like this so I'm lost.
This is the validation I wrote for the servver side and now I want the exact same only on client side. I hoping someone will be able to either do this one so I can use it as a basis to build the other validations or possibly help me to figure out how to do it.
I found some examples but they seemed to be very simple examples

  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null) return null;

            string _value = value.ToString();
 
            string[] m = new string[]
            {
                "0", "1"
            };
            foreach (string s in m)
            if (_value.StartsWith(s)) { return new ValidationResult("Phone number cannot start with " + s); }
            if (_value.Substring(1, 2) == "11") { return new ValidationResult("Phone number cannot start with " + _value.Substring(0,3)); }
            if (_value.Substring(4, 2) == "11") { return new ValidationResult("Phone number is not valid"); }         
              
            foreach (string s in m)
                if (_value.Substring(3, 1) == s) { return new ValidationResult("Invalid phone number"); }           
                if (_value.Distinct().Count() == 1) { return new ValidationResult("Invalid phone number"); }

            return ValidationResult.Success;

        }

       #region IClientValidatable Members

       public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
       {
           var rule = new ModelClientValidationRule()
           {
               ValidationType = "phonenumber",
               ErrorMessage = FormatErrorMessage(metadata.DisplayName),
           };
           rule.ValidationParameters["name"] = PhoneNumber;
           yield return rule;
       }
       #endregion
    }

Open in new window


Thank you in advance
Niall292Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
Make sure that you continue your serverside validation.  

Instead of writing something from scratch, there is a  jquery plug in you can use http://jqueryvalidation.org/documentation/

You just need to add the required to the input.

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Please provide your name, email address (won't be published) and a comment</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required/>
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required/>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url"/>
    </p>
    <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit"/>
    </p>
  </fieldset>
</form>
<script>
$("#commentForm").validate();
</script>

Open in new window

0
leakim971PluritechnicianCommented:
Test page : http://jsfiddle.net/nxGfg/
var ValidationResult = function(message) {
    alert(message);
    return false;
}

var IsValid = function(value) {
    //if (value == null) return null;
    if (value == null) return null;

    //string _value = value.ToString();
    var _value = value.toString(); // useless...

    //string[] m = new string[]
    //{
    //    "0", "1"
    //};
    var m = ["0", "1"]

    //foreach (string s in m)
    for(var s=0;s< m.length;s++)
    //if (_value.StartsWith(s)) { return new ValidationResult("Phone number cannot start with " + s); }
    if (_value.charAt(0)==m[s]) { return ValidationResult("Phone number cannot start with " + m[s]); }

    //if (_value.Substring(1, 2) == "11") { return new ValidationResult("Phone number cannot start with " + _value.Substring(0,3)); }
    if (_value.substring(0, 2) == "11") { return ValidationResult("Phone number cannot start with " + _value.substring(0,2)); }
    //if (_value.Substring(4, 2) == "11") { return new ValidationResult("Phone number is not valid"); }
    if (_value.substring(3, 2) == "11") { return ValidationResult("Phone number is not valid"); }

    //foreach (string s in m)
    for(var s=0;s< m.length;s++)
    //if (_value.Substring(3, 1) == s) { return new ValidationResult("Invalid phone number"); }
    if (_value.substring(2, 1) == s) { return ValidationResult("Invalid phone number"); }

    //if (_value.Distinct().Count() == 1) { return new ValidationResult("Invalid phone number"); }
    var Count = 0;
    for(var i=0;i<_value.length;i++) if(_value.charAt(i).indexOf(_value)>=0) Count++;
    if(Count==1) return ValidationResult("Invalid phone number");

    return true;
}

var n = "4567890123";
if(IsValid(n) === true ) alert("good number!")

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Niall292Author Commented:
Padas,
I knew there already was a validation js plugin but I did not know you could add to it (as I said this is my first time doing something like this) and will definitely look into the docs you sent me the link for.

leakim971,
Your answer definitely is what I asked for and thank you. I have another question do I just drop this into a new .js file and I seen some other websites saying I would need to register it with the validate.js something like.

$.validator.addMethod("phonecheck", function (value, element) {
    return false;

Do I just put that at the start. You both have already answered my question but again I am  new to this and not sure how to set it up

Thanks again
0
Niall292Author Commented:
Thanks for the 2 answers. I think I will be able load this to a validate plugin between the 2 answers.

Thanks again
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.