[英]Stop form submission
我有一个显示带有文本输入和按钮的表单的脚本。 文本输入是必需的,但脚本仅验证输入是否为空/非空。
我需要更进一步,以便它仅验证字母数字。
我无权访问处理表单提交/验证的文件,因为有 1000 个文件。
如果输入字段不是字母数字,我尝试了这个脚本来尝试停止表单提交。 但它不起作用,无论输入如何,表单仍然提交。 我彻底测试了validate_text_field()
并且运行良好。
<script>
jQuery(document).ready(function() {
function validate_text_field( input_txt_val ){
var letters = /^[0-9a-zA-Z]+$/;
input_txt_val = $.trim( input_txt_val );
if( input_txt_val.match(letters) ){
return true;
}else{
return false;
}
}
jQuery(".asp_product_buy_btn_container .pricing-button").click(function(e){
var input_txt_val = $( this ).closest( '.asp_all_buttons_container' ).siblings( 'form.asp-stripe-form' ).find( ".asp_product_custom_field_input" ).val();
var is_valid = validate_text_field( input_txt_val );
if( is_valid ){
alert('is valid alphanumeric');
return true;
}else{
alert('is not valid alphanumeric');
e.preventDefault()
return false;
}
});
});
</script>
如何阻止提交此表单?
preventDefault()` 当它无效时。 事件处理程序的返回值可能无法正确处理。
jQuery(document).ready(function() {
jQuery("#stripe_button_0").click(function(e){
var is_valid = validate_text_field();
if( is_valid ){
return true;
}else{
e.preventDefault()
return false;
}
});
});
在您的 URL 中,如果您调用 validate_text_field() 我会收到一个错误:
ReferenceError: validate_text_field is not defined
所以首先尝试解决这个问题。
两个提示:您可以使用 $ 代替 'jQuery'。 另外,这个片段:
var is_valid = validate_text_field();
if( is_valid ){
return true;
}else{
return false;
}
可以减少到
return validate_text_field();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.