#javascript #jquery #validation #grails
#javascript #jquery ( jquery ) #валидация #grails
Вопрос:
ниже приведен пример проверки формы с использованием jquery, который я скопировал из Интернета,
однако, когда я использовал <g:form>
вместо <form>
проверки, функция не работала.
Пожалуйста, предложите лучший способ проверки формы с помощью groovy form
Спасибо
<html>
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<link href="runnable.css" rel="stylesheet" />
<!-- Load jQuery and the validate plugin -->
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<!-- jQuery Form Validation code -->
<script>
// When the browser is ready...
$(function() {
// Setup form validation on the #register-form element
$("#register-form").validate({
// Specify the validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
},
agree: "required"
},
// Specify the validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
</head>
<body>
<h1>Register here</h1>
<!-- The form that will be parsed by jQuery before submit -->
<form action="" method="post" id="register-form" novalidate="novalidate">
<div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
<div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
<div class="label">Email</div><input type="text" id="email" name="email" /><br />
<div class="label">Password</div><input type="password" id="password" name="password" /><br />
<div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
</form>
</body>
</html
Комментарии:
1. Можете ли вы проверить, что элемент формы, созданный <g:from> в браузере, совпадает с элементом <form>, который вы использовали в противном случае.
2. Ну, когда я использовал <g:form> и нажал на кнопку, он выполняет действие отправки, прежде чем я проверю поля.
3. Возможно, вы можете перейти к ViewSource своей страницы в браузере и сравнить html, сгенерированный при использовании <g:form>
Ответ №1:
Ваш <form>
тег содержит novalidate
атрибут, который указывает, что форма не должна проверяться при отправке, сначала избавьтесь от него. Ниже приведен пример кода из тестового проекта для использования проверки jquery <g:form>
. Извините за длинный код.
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="esn-registration">
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("emailId", function(value, element) {
return this.optional(element) || /^[A-Z0-9._% -] @[A-Z0-9.-] .[A-Z]{2,4}$/i.test(value);
}, "Email is invalid: Enter a valid email");
$.validator.addMethod("username", function(value, element) {
return this.optional(element) || /^[a-z][w.-]{3,20}$/i.test(value);
}, "Characters, numbers, ( _ ), ( - ) and ( . ) only");
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstName: "required",
lastName: "required",
emailId: {
required: true,
email: true,
emailId: true
},
username: {
required: true,
minlength: 3,
maxlength: 20,
username: true
},
password: {
required: true,
minlength: 6
}
},
messages: {
firstName: { required: "Please enter your first name" },
lastName: { required: "Please enter your last name" },
emailId: {
required: "Please enter an email address",
email: "Please enter a valid email address"
},
username: {
required: "Please enter an username",
minlength: "Username must exceed 3 characters",
maxlength: "Username cannot exceed 20 characters"
},
password: {
required: "Please provide a password",
minlength: "Password must exceed 6 characters"
}
},
submitHandler: function(form) {
if(signupForm.valid()){
form.submit();
$('button[type="submit"]').removeAttr('disabled');
} else {
$('button[type="submit"]').attr('disabled','disabled');
}
}
});
// validate login form on keyup and submit
$("#loginForm").validate({
rules: {
username: "required",
password: {
required: true,
minlength: 6
}
},
messages: {
username: {
required: "Please enter an username or email",
},
password: {
required: "Please provide a password",
minlength: "Password must exceed 6 characters"
}
},
submitHandler: function(form) {
if(loginForm.valid()){
form.submit();
$('button[type="submit"]').removeAttr('disabled');
} else {
$('button[type="submit"]').attr('disabled','disabled');
}
}
});
// propose username by combining first and lastname
$("#username").focus(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
if(firstName amp;amp; lastName amp;amp; !this.value) {
this.value = $.trim(firstName) "." $.trim(lastName);
}
});
});
</script>
<title>ESN</title>
</head>
<body>
<div class="front-card">
<div class="front-welcome">
<div class="front-welcome-text">
<h3>Welcome</h3>
</div>
</div>
<div class="front-login">
<g:form name="loginForm" controller="login" action="validate"
method="POST" class="form well well-small container-fluid span3.5">
<div id="login-form">
<div class="placeholding-login-username">
<input id="user-name" name="username"
value="${loginInstance?.username }"
placeholder="Username or email" class="input-xlarge" type="text"
maxlength="100" required/>
</div>
<div class="placeholding-login-password">
<input id="password" name="password"
value="${loginInstance?.password }"
placeholder="Password(min. length 6)" class="input-xlarge"
type="password" maxlength="30" required/>
</div>
<g:if test="${message}">
<div class="message text-error" role="status">
<ul class="errors" role="alert">
<li>
${message}
</li>
</ul>
</div>
</g:if>
<div class="button pull-right">
<button name="submit" class="btn" type="submit">Login</button>
</div>
</div>
</g:form>
</div>
<div class="front-signup">
<g:form name="signupForm" action="save" method="POST"
class="form well well-small container-fluid span3.5">
<div id="signup-form">
<fieldset class="form">
<legend>
<h5>
<strong class="muted">New to ESN?</strong> <strong
class="text-info"> Sign up</strong>
</h5>
</legend>
<div class="placeholding-first-name">
<input id="firstName" name="firstName"
value="${userInstance?.firstName}" placeholder="First name"
class="input-xlarge" type="text" maxlength="150" required/>
</div>
<div class="placeholding-last-name">
<input id="lastName" name="lastName"
value="${userInstance?.lastName}" placeholder="Last name"
class="input-xlarge" type="text" maxlength="150" required/>
</div>
<div class="placeholding-email-id">
<input id="emailId" name="emailId"
value="${userInstance?.emailId}" placeholder="Email Id(Corporate)"
class="input-xlarge" type="email" maxlength="100" required/>
</div>
<div class="placeholding-signup-username">
<input id="username" name="username"
value="${userInstance?.username}" placeholder="Username"
class="input-xlarge" type="text" maxlength="20" required/>
</div>
<div class="placeholding-signup-password">
<input id="password" name="password"
value="${userInstance?.password}"
placeholder="Password(min. length 6)" class="input-xlarge"
type="password" maxlength="30" required/>
</div>
</fieldset>
<fieldset class="button pull-right">
<button id="submit" name="submit" class="btn btn-primary" type="submit">Sign
up</button>
</fieldset>
<div>
<g:if test="${blankMessage}">
<div class="message text-error" role="status">
<ul class="errors" role="alert">
<li>
${blankMessage}
</li>
</ul>
</div>
</g:if>
<g:hasErrors bean="${userInstance}">
<div class="text-error">
<ul class="errors" role="alert">
<g:eachError bean="${userInstance}" var="error">
<li
<g:if test="${error in org.springframework.validation.FieldError}">data-field-id="${error.field}"</g:if>><g:message
error="${error}" /></li>
</g:eachError>
</ul>
</div>
</g:hasErrors>
</div>
</div>
</g:form>
</div>
</div>
</body>
</html>
Комментарии:
1. Спасибо, брат, это дало мне новую идею, я действительно ценю твою помощь.
2. Добро пожаловать, брат. Я рад, что это не только помогло вам, но и дало вам новую идею.