[Angularjs]表单验证

写在前面

在开发中提交表单,并对表单的值进行验证是非常常见的操作,angularjs对表单验证提供了非常好的支持。

demo

表单

<form name="myform" novalidate action="../api/order/lists/add" method="post">
    <p>
        <input type="text" name="name" ng-model="order.name" value="" required />
        <span style="color:red" ng-show="myform.name.$dirty && myform.name.$invalid">
            <span ng-show="myform.name.$error.required">订单名称是必须的。</span>
        </span>
    </p>
    <p>
        <input type="text" name="price" ng-model="order.price" value="" required />
        <span style="color:red" ng-show="myform.price.$dirty && myform.price.$invalid">
            <span ng-show="myform.price.$error.required">单价是必须的。</span>
        </span>
    </p>

    <input type="submit" name="name" ng-disabled="myform.name.$dirty && myform.name.$invalid ||
  myform.price.$dirty && myform.price.$invalid" />
</form>

服务端

        [HttpPost]
        [Route("api/order/lists/add")]
        public async Task<HttpResponseMessage> Post([FromBody] Order order)
        {
            return await Task.Factory.StartNew(() =>
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Accepted);
                order.Id = Guid.NewGuid();
                lstOrders.Add(order);
                response = new HttpResponseMessage(HttpStatusCode.Accepted)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = lstOrders }))
                };
                return response;
            });
        }

测试

提交后数据

总结

$dirty:表单有填写记录

$valid:字段内容合法的

$invalid:字段内容是非法的

$pristine:表单没有填写记录

posted @ 2016-05-15 10:32  wolfy  阅读(490)  评论(0编辑  收藏  举报