Help, please, do field validation. I would have the usual required, but it does not work in Safari.

I have this form:

$(".form").submit(function() { $.ajax({ type: "POST", url: "mail.php", data: $(this).serialize() }).done(function() { $(this).find("input").val(""); alert("Отправлено"); $(".form").trigger("reset"); }); return false; }); 
 <form class="form"> <input type="text" placeholder="Ваше имя" name="name"> <input type="text" placeholder="Ваш телефон *" required="" name="phone"> <button class="button">Отправить визитку</button> </form> 

It is desirable to show an example based on my form, for understanding.

    2 answers 2

    By analogy, and the phone, for the phone there are jquery plugins with a mask, checking for numbers, etc.

     $("#submit").click(function() { //ЕСЛИ СИМВОЛОВ ИМЕНИ > 4 И СИМВОЛОВ ТЕЛЕФОНА >10 if ($('#name').val().length > 4 && $('#phone').val().length > 10) { //ОТПРАВЛЯЕТЕ ФОРМУ alert('success'); } //ЕСЛИ УСЛОВИЕ НЕ ВЫПОЛНЕНО else { //УВЕДОМЛЯЕТЕ ПОЛЬЗОВАТЕЛЯ АЛЕРТОМ/БЛОКОМ/ЛЮБЫМ ВАМ УДОБНЫМ СПОСОБОМ И НЕ ОТПРАВЛЯЕТЕ ФОРМУ alert('warning'); return false; } }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <form class="form"> <input type="text" placeholder="Ваше имя" name="name" id="name"> <input type="text" placeholder="Ваш телефон *" required="" name="phone" id="phone"> <button class="button" id="submit">Отправить визитку</button> </form> 

    • I understand it, we process click. But I need to do a check before submitting the form. How to do it? Now check and send work by themselves. For example, in safari I will get an error that the field is not filled, but the form will still go. - Alexander
    • add after the if block else in which and send. If the condition is satisfied (in the example, change "<4" to "> 4"), then send the form, if it is not executed, do not send and notify the user. I'll fix the code now. - nueq
    • return false; after alert('warning'); - Igor
    • @Igor thanks, I'll add now - nueq

    The .val (value) method in jQuery sets the element's value . Just the .val () method returns the current value of the element. You can do this: we find the item we check or the field is filled, if yes then alert if not then nul

     $(this).find("input").val().length > 0 ? alert("Отправлено") : null