廢話不多說,我們直接上程式碼!這裡以
laravel
,vue
,vue-apollo
為例
這裡涉及到其他外掛的配置使用,請參考連結:
- vue:https://github.com/vuejs/vue
- vue-apollo: https://github.com/Akryum/vue-apollo
- vee-validate:https://github.com/baianat/vee-validate
namespace YouNamespace;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Query;
use App\Contracts\UserInterface;
use App\User;
class UserFieldQuery extends Query
{
protected $attributes = [
'name' => 'User field Query'
];
public function type()
{
return Type::boolean();
}
public function args()
{
return [
'field' => [
'type' => Type::nonNull(Type::string()),
],
'value' => [
'type' => Type::nonNull(Type::string()),
]
];
}
public function resolve($root, $args)
{
[$field, $value] = array_values($args);
// 定義合法的欄位驗證。
switch ($field) {
case 'mobile_phone':
return User::findByMobilePhone($value) instanceof UserInterface;
break;
case 'nikename':
return User::findByNikename($value) instanceof UserInterface;
break;
}
return false;
}
}
新增查詢到配置檔案
config/graphql.php
'schemas' => [
'default' => [
'query' => [
'user_field_exist' => 'YouNamespace\UserFieldQuery'
],
// ...
]
]
import gql from 'graphql-tag';
import graphqlClient from '@/graphql';
class AsynFieldRemoteValidator {
static async queryUserFieldUnique(field, value) {
const {data} = await graphqlClient.query({
query: gql`query UserFieldQuery($field: String!, $value: String!){
user_field_exist(field: $field, value: $value)
}`,
variables: {
field: field,
value: value
}
});
return data;
}
}
export default AsynFieldRemoteValidator;
你的vue元件。在
created()
方法定義
import AsynFieldRemoteValidator from '@/support/asyn-field-remote-validator';
this.$validator.extend('unique_user_field', {
getMessage(field, params, data) {
return this.$t('core.message.unique_field', {field});
},
async validate(value, args) {
const field = args[0];
let result = value
// 這裡判斷驗證手機號碼時處理手機號碼格式。使用`libphonenumber-js` 參考:https://github.com/catamphetamine/libphonenumber-js, 這裡不多介紹`libphonenumber-js`使用
if (field === 'mobile_phone') {
result = parseIncompletePhoneNumber(value, local.alias.toUpperCase());
}
const {user_field_exist} = await AsynFieldRemoteValidator.queryUserFieldUnique(field, result);
return {
valid: user_field_exist === false,
data: {
field: result
}
};
}
})
<input
type="tel"
v-model="mobile_phone"
:placeholder="188 **** ****"
:state="validateState('mobile_phone')"
:data-vv-as="手機號碼"
name="mobile_phone"
v-validate="'required|mobile_pohone_format|unique_user_field:mobile_phone'"
文章寫得非常粗暴,大神多多指教!