通过自定义属性

时间:2016-03-15 14:57:08

标签: javascript html

请帮我通过输入标签的自定义属性进行验证(在我的情况下:验证)。帮助我改变我的代码,使其变得更加动态和可重用。

 var validation = function validation(){// out of grid - rename js name

        //validate first name - only letters
        var only_letters = /^[A-Za-z]+$/;// allow only letters

        if(firstName.value.length === 0){
            document.getElementsByClassName("error")[0].innerHTML="First Name is required";
            formIsValid = false;
        }
        else
        if(firstName.value.match(only_letters)){
            document.getElementsByClassName("error")[0].innerHTML="";
        }
        else{
            document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
            formIsValid = false;
        }

        //validate email

        var email_letters = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

        if(email.value.length === 0){
            document.getElementsByClassName("error")[2].innerHTML="Email is required";
            formIsValid = false;
        }
        else
        if(email.value.match(email_letters)){
            document.getElementsByClassName("error")[2].innerHTML="";
        }
        else{
            document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
            formIsValid = false;
        }
<form id="user_form" method="post">

    <p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
    <span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
  </form>

2 个答案:

答案 0 :(得分:0)

如果你仔细看,你只有一种方法,它的本质。 创建一个获取元素,正则表达式,响应容器并返回字符串的方法。

它看起来像这样:

function validateMePls(var field, var regex, var placeholder){
    var isValid = "";
    /** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};

var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);

/** and now you check 'isValid' for something in it, so you know if you have an error or not */

这基本上是代码的优化版本的样子。

抱歉接近Java&#39;代码,但我最近没有做任何Javascript。

祝你好运。

答案 1 :(得分:0)

您可以在placeholder活动中使用required属性,setCustomValidity()属性,placeholder设置为invalid

&#13;
&#13;
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
  inputs[i].oninvalid = function(e) {
    e.target.setCustomValidity(e.target.placeholder)
  }
}
&#13;
<form id="user_form" method="post">

  <label for="first_name">
    <input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
  </label>
  <br>

  <label for="email">
    <input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
  </label>
  <br>
  <input type="submit" />
</form>
&#13;
&#13;
&#13;