2013-09-05 27 views
6

Tôi đang cố xử lý xác thực biểu mẫu khi nhấp vào nút. Nó đang xác thực biểu mẫu nhưng không hiển thị lỗi. ai cũng có thể giúp tôi trong việc này không?Kích hoạt xác thực html5 theo cách thủ công trên nút bấm

<form id="the-form" action="#"> 
    <input type="text" required="required" placeholder="Required text" /> 
    <input type="email" required="required" placeholder="email" /> 
    <button id="btn" type="button">Submit</button> 
</form> 

javascript:

$("#btn").on("click", function(){ 
    if($("#the-form")[0].checkValidity()) 
    { 
     alert('validated'); 
    } 
    else 
    { 
     //show errors 
     return false; 
    } 
}); 

http://jsfiddle.net/5ycZz/

Trả lời

3

tôi đã đạt được điều này bằng cách thực hiện các bước dưới đây:

1) Tôi đang gặp dạng:

<form> 
    <textarea required></textarea> 
    <input type="submit" style="display:none;"/> 
</form> 

<a>Some other button to trigger event</a> 

2) Bây giờ chúng ta phải kiểm tra xem dạng là điền chính xác:

//this is <a> click event: 
if (!$('form')[0].checkValidity()) { 
    $('form').find('input[type="submit"]').click(); 
    return false; 
} 

Điều này sẽ kích hoạt gửi nhưng không gửi vì có lỗi;)

Dường như lỗi xác nhận html5 được hiển thị trên đầu vào [type = "submit"] nhấp :)

Hope sẽ làm việc cho bạn quá! :)

0

Tháo tuyên bố khác. (Cập nhật)

$("#btn").on("click", function(){ 
if($("#the-form")[0].checkValidity()) 
{ 
    alert('validated'); //will appear if name and email are of valid formats 
} 
}); 
+0

tôi không muốn thể hiện sai sót trong báo nó sẽ hiển thị lỗi trong popover bootstrap đó là hành vi mặc định của html5 –

+0

@ImranRashid Tôi hiểu rồi. Xóa tuyên bố 'khác': else { // hiển thị lỗi cảnh báo ('không được xác thực'); } – Elmer

+0

kiểm tra trên http://jsfiddle.net/5ycZz/ .. nếu tôi thay đổi loại nút để gửi nó hoạt động nếu không nó hiển thị không có msg –

3

đây là câu trả lời hoàn hảo

<form id="the-form" action="#"> 
<input type="text" required="required" placeholder="Required text" /> 
<input type="email" required="required" placeholder="email" /> 
<button id="btn" type="submit">Submit</button> 

$("#btn").on("click", function(){ 
if($("#the-form")[0].checkValidity()) 
{ 
    alert('validated'); 
} 
else 
{ 
    return 0; 
} 

});

-1

Bạn có thể chỉ cần thêm onclick = "return validateForm()".

<button id="btn" onclick="return validateForm()" type="button">Submit</button> 
4

Hãy thử

reportValidity() 

Vì vậy, bạn sẽ phải

$("#btn").on("click", function(){ 
    if($("#the-form")[0].checkValidity()) { 
     alert('validated'); 
    } 
    else { 
     $("#the-form")[0].reportValidity(); 
    } 
}); 
+0

hoàn hảo! https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reportValidity – WayFarer

Các vấn đề liên quan